//    Copyright (C) Kherty.  All rights reserved.
using System;
using OpenLS.Core.Serialization;

namespace OpenLS.Spreadsheet
{
    public class CustomFilter: IOfficeXmlSerializable
    {
        #region IOfficeXmlSerializable Members

        void IOfficeXmlSerializable.ReadXml(ReadContext context)
        {
            using (ReadContext c = context.Read("customFilter"))
            {
                Operator = c.GetOptionalEnum("operator", FilterOperator.Equal);
                val = c.GetOptionalString("val");
            }
        }

        void IOfficeXmlSerializable.WriteXml(WriteContext context)
        {
            using (WriteContext c = context.Write("customFilter"))
            {
                c.SetOptionalEnum("operator", Operator, FilterOperator.Equal);
                c.SetOptionalString("val", val);
            }
        }

        #endregion

        private string val;

        public string Value
        {
            get { return val; }
            set { val = value; }
        }
	

        private FilterOperator _operator;

        public FilterOperator Operator
        {
            get { return _operator; }
            set { _operator = value; }
        }


        internal bool GetValue(Cell cell)
        {
            object value = cell.Value;
            if (value is double)
            {
                double a;
                double.TryParse(Value, out a);
                int i =  ((double)value).CompareTo(a);
                return GetValueFrom(i);
            }
            if (value is string)
            {
                int i = ((string)value).CompareTo(Value);
                return GetValueFrom(i);
            }
            if (value == null)
                return false;
            throw new NotImplementedException();
        }

        private bool GetValueFrom(int i)
        {
            switch (Operator)
            { case FilterOperator.Equal: return i == 0;
                case FilterOperator.GreaterThan :return i > 0;
                case FilterOperator.GreaterThanOrEqual: return i >= 0;
                case FilterOperator.LessThan: return i < 0;
                case FilterOperator.LessThanOrEqual: return i <= 0;
                case FilterOperator.NotEqual: return i != 0;
                default: throw new NotSupportedException();
            }
        }
    }
}
